
import { useState, useRef, useEffect } from 'react'
import './App.css'

type User = {
  name: string
  age: number
}
// 限制props参数必须有className（必填），且值为string
type Props = {
  className: string
  title?: string //添加？表示为可选参数，非必传
  children: React.ReactNode
  onGetMsg?: (msg: string) => void
}
// interface Props{
//   className:string,
//   title?:string
// }
function Button(props: Props) {
  const { className, children, onGetMsg } = props
  const clickHandler = () => {
    onGetMsg?.('123')
  }
  return (
    <>
      <button className={className} onClick={clickHandler}>
        {children}
      </button>
    </>
  )
}
function App() {
  const [count, setCount] = useState(false)
  setCount(true)
  const [list, setList] = useState([1, 2, 3])
  setList([1])

  // const [user,setUser] = useState<User>()
  // const [user0,setUser0] = useState<User>({name:'wwx',age:18})
  // const [user1,setUser1] = useState<User>(()=>({name:'wwx',age:18}))
  // setUser(undefined) //setUser的参数可以为undefined
  // setUser0({name:'wwx',age:18}) // 参数可以为对象
  // setUser1(()=>({name:'wwx',age:18})) // 参数可以为函数返回对象

  const [user, setUser] = useState<User | null>(null)
  const changeUser = () => {
    setUser(null)
    setUser({
      name: 'wwx',
      age: 18,
    })
  }
  const getMsgHandler = (msg: string) => {
    console.log(msg)
  }

  const domRef = useRef<HTMLInputElement>(null)
  useEffect(() => {
    // 可选链 前面不为空值（null/undefined）时执行点运算
    // 类型守卫 防止出现空值点运算错误
    domRef.current?.focus()
  }, [])

  // 稳定引用的存储器（定时器管理）
  const timerid = useRef<number | undefined>(undefined)
  useEffect(() => {
    // timerid.current的类型需要为number或undefined，定时器的类型为number，符合类型约束
    timerid.current = setInterval(() => {
      console.log('123')
    }, 1000)
    // 销毁定时器，timerid.current的值为undefined，符合类型约束
    return () => clearInterval(timerid.current)
  })
  return (
    <>
      <div>{count}</div>
      {list.map((item) => (
        <div>{item}</div>
      ))}
      {/* <div>{user?.name},{user0.name},{user1.name}</div> */}
      <div onClick={changeUser}>{user?.name}</div>
      <Button className="test" onGetMsg={(msg) => console.log(msg)}>
        Click me!
      </Button>
      <Button className="test" onGetMsg={getMsgHandler}>
        <span>this is a span</span>
      </Button>
      <input ref={domRef} />
    </>
  )
}

export default App
